home *** CD-ROM | disk | FTP | other *** search
- Path: news.th-darmstadt.de!news
- From: Enno Sandner <enno@intellektik.informatik.th-darmstadt.de>
- Newsgroups: comp.lang.c++
- Subject: Re: Creating an object via new with ONLY a pointer to the object
- Date: Thu, 11 Apr 1996 15:08:44 +0200
- Organization: Fachbereich Informatik, TH Darmstadt
- Message-ID: <316D045C.59E2B600@intellektik.informatik.th-darmstadt.de>
- References: <4kh07v$lno@crchh327.rich.bnr.ca>
- NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.01 (X11; I; SunOS 4.1.3 sun4m)
-
- Bret Bieghler wrote:
- >
- > An interesting problem I've come across... I was wondering if this
- > is possible:
- >
- > I have a generic CommandObject which defines several pure virtual
- > functions. Derived from CommandObject are user commands, such
- > as ExitCommand, StatusCommand, etc.
- >
- > To process a command (currently) I do the following:
- >
- > CommandObject* basePtr;
- >
- > if (command == "exit")
- > {
- > basePtr = new ExitCommand;
- > basePtr->implement();
- > }
- > else if (command == "status")
- > {
- > basePtr = new StatusCommand;
- > basePtr->implement();
- > }
- >
- > What I would LIKE to do is the the following:
- >
- > CommandObject* basePtr = new commandTable[command];
- >
- > where commandTable is an associative array as follows:
- >
- > Key Value
- > "exit" ExitCommand*
- > "status" StatusCommand*
- >
- > The problem is if there is a way to create a new object
- > of a given type having only a pointer to that type.
- >
- > Is this possible?
- >
-
- There's no direct languages support for such a thing in C++, but
- you can maintain a set of (<command-name>,<creation-func>) tuples
- in a map. The <creation-func> is a func of type 'CommandObject* (*)()'
- which returns a newly created object of the appropriate subclass
- of 'CommandObject'. You may choose these functions as static
- member-functions of the subclasses of 'CommandObject', e.g.
-
- class MyOwnCommand : public CommandObject {
- ...
- public:
- static CommandObject* Create() {
- return new MyOwnCommand;
- }
- ...
- };
-
- There're several other solutions but this one is IMO the minimal
- extension of the idea you already had.
-
- Enno
-